package caches

// refresh  info in current project

import (
	cloud "cloud_android_backend/pkg/models/cloud"
	user "cloud_android_backend/pkg/models/users"
	"time"

	"github.com/golang/glog"
	lru "github.com/hashicorp/golang-lru"
	"github.com/jinzhu/gorm"
	"modules.tenxcloud.com/common/composite"
)

const ResourceAliasNameSuffix = "-aliasname"

var (
	caches, _    = lru.New(65535)
	syncDuration = time.Minute * 5
)

func init() {
	db, err := composite.Database.GetOrm()
	if err != nil {
		glog.Fatal(err)
	}
	handler(db)
	go syncCluster(db)
}

func Cache() *lru.Cache {
	return caches
}

func syncCluster(db *gorm.DB) {
	ticker := time.NewTicker(syncDuration)
	for _ = range ticker.C {
		handler(db)
	}

}

func handler(db *gorm.DB) {
	caches.Purge()
	cloudresources, err := cloud.NewResourceRepository(db).ListCloudResource(nil)
	if err != nil {
		glog.Error(err)
	} else {
		for _, res := range cloudresources {
			caches.Add(res.CloudResourceID, res.Name)
			caches.Add(res.CloudResourceID+ResourceAliasNameSuffix, res.AliasName)
		}
	}

	flavors, err := cloud.NewResourceSpecRepository(db).ListComputeFlavor()
	if err != nil {
		glog.Error(err)
	} else {
		for _, flavor := range flavors {
			caches.Add(flavor.FlavorID, flavor.Name)
		}
	}

	users, _, err := user.New().List(db, nil, nil, 0, 0)
	if err != nil {
		glog.Error(err)
	} else {
		for _, u := range users {
			caches.Add(u.UserID, u.UserName)
		}
	}
}
